<script setup>
	import { onMounted, ref } from "vue";
	import MenuItem from "./MenuItem.vue";
	import routerMap from "@/router/routerMap";
	import router from "@/router";

	let selectedKeys = ref([]);
	let openKeys = ref([]);
	let menuRef = ref();

	let menu = initDefaultKeys(routerMap);
	
	if (menu) {
		openKeys.value = menu.openKeys;
		selectedKeys.value = menu.selectedKeys;
	}

	function initDefaultKeys(menuList) {
		let openKeys = [], selectedKeys = [];
		for (let i = 0; i < menuList.length; i++) {
			openKeys = [];
			let menu = menuList[i];
			if (menu.children) {
				openKeys.push(menu.id);
				let result = initDefaultKeys(menu.children);
				if (result.selectedKeys.length) {
					openKeys.push(...result.openKeys);
					selectedKeys.push(...result.selectedKeys);
					return { openKeys, selectedKeys };
				}
			}
			else if (menu.path) return { openKeys, selectedKeys: [menu.id] };
		}
		return { openKeys, selectedKeys };
	}

	function selectHandler({ keyPath, item }) {
		openKeys.value = keyPath;
		if (item) {
			if (item.path) {
				router.push(item.path);
			}
		}
	}

	onMounted(() => {
		console.log(menuRef.value)
	})
</script>

<template>
	<a-menu theme="light" mode="inline" @select="selectHandler" v-model:openKeys="openKeys" v-model:selectedKeys="selectedKeys" ref="menuRef">
		<template v-for="item in routerMap">
			<MenuItem :item="item" />
		</template>
	</a-menu>
</template>

<style scoped lang="less"></style>
